package com.idealighter.game.server.core.task;

import com.idealighter.game.server.handler.HandlerFactory;
import com.idealighter.game.server.handler.HttpReqMessageHandler;
import com.idealighter.game.server.net.http.ReqHttpMessage;
import com.idealighter.game.server.net.http.ResHttpMessage;

import io.netty.handler.codec.http.HttpResponseStatus;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 请求消息task .
 */
public class ReqHttpMsgTask implements Runnable {

  private static final Logger LOG = LoggerFactory.getLogger(ReqHttpMsgTask.class);
  private static final Logger MSGHANDLER_LOG = LoggerFactory.getLogger("MsgHandlerLog");

  private final ReqHttpMessage msg;

  /**
   * 构造函数 .
   * 
   * @param msg . 消息.
   */
  public ReqHttpMsgTask(ReqHttpMessage msg) {
    super();
    this.msg = msg;
  }

  @Override
  public final void run() {
    try {
      String path = msg.getPath();
      ResHttpMessage result = null;
      HttpReqMessageHandler handler = HandlerFactory.getHttpHandler(path);
      if (handler != null) {
        result = handler.action(msg);
        msg.sendResponse(result);
        MSGHANDLER_LOG.info("处理消息成功：{}", path);
      } else {
        msg.sendError(HttpResponseStatus.NOT_FOUND);// HttpResponseStatus.NOT_FOUND);
      }
    } catch (Exception exception) {
      msg.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR);
      LOG.error("未处理清楚的异常[" + msg.getPath() + "]执行异常", exception);
    }
  }
}
